﻿using DBUtil.Attributes;
using DotNetCommon.Extensions;
using NUnit.Framework;
using Shouldly;
using System.ComponentModel.DataAnnotations.Schema;

namespace Test.MySql.ColumnTypeTests
{
    [TestFixture]
    internal class ColumnTypesTestsBool : TestBase
    {
        #region model
        [Table("test")]
        public class Person
        {
            [PrimaryKey(KeyStrategy = KeyStrategy.Identity)]
            [Column("id")]
            public int Id { get; set; }

            public bool p_bool { get; set; }
            public bool? p_bool_null { get; set; }
        }
        #endregion

        [SetUp]
        public void SetUp()
        {
            DropTableIfExist("test");
            db.ExecuteSql("""
                create table test(id int primary key auto_increment,p_bool bit(1),p_bool_null bit(1))
                """);
            db.ExecuteSql("""
                insert into test(p_bool,p_bool_null) values
                    (1,1),
                    (0,null),
                    (0,0);
                """);
        }

        [Test]
        public void TestSelect()
        {
            var select = db.Select<Person>().Where(i => i.p_bool);
            var sql = select.ToSqlList();
            sql.ShouldBe("""
                select t.id `Id`,t.`p_bool`,t.`p_bool_null`
                from test t
                where t.`p_bool`;
                """);
            var list = select.ToList();
            var json = list.ToJson();
            json.ShouldBe("""[{"Id":1,"p_bool":true,"p_bool_null":true}]""");

            var select2 = db.Select<Person>().Where(i => !i.p_bool_null.Value || i.p_bool_null == null);
            var sql2 = select2.ToSqlList();
            sql2.ShouldBe("""
                select t.id `Id`,t.`p_bool`,t.`p_bool_null`
                from test t
                where (not (t.`p_bool_null`)) or (t.`p_bool_null` is null);
                """);
            var list2 = select2.ToList();
            var json2 = list2.ToJson();
            json2.ShouldBe("""[{"Id":2,"p_bool":false,"p_bool_null":null},{"Id":3,"p_bool":false,"p_bool_null":false}]""");
        }

        [Test]
        public void TestUpdate()
        {
            var update = db.Update<Person>().SetEntity(new Person { Id = 1, p_bool = false, p_bool_null = null });
            var sql = update.ToSql();
            sql.ShouldBe("""
                update test set
                    `p_bool` = 0,
                    `p_bool_null` = null
                where id = 1;
                """);
            var r = update.ExecuteAffrows();
            r.ShouldBe(1);

            var list = db.Select<Person>().ToList();
            var json = list.ToJson();
            json.ShouldBe("""[{"Id":1,"p_bool":false,"p_bool_null":null},{"Id":2,"p_bool":false,"p_bool_null":null},{"Id":3,"p_bool":false,"p_bool_null":false}]""");
        }
    }
}
